﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using EHTSaleManager.Code.BLL;
using EHTSaleManager.Code.Entity;
using EHTSaleManager.Code.Utility;
using System.Data;
using System.IO;

using System.Drawing;
using System.Drawing.Drawing2D;

namespace EHTSaleManager.UIAdmin
{
    public partial class AdminProduct : System.Web.UI.Page
    {
        public Int32 ProductID = -1;
        public Int32 categoryID = -1;
        private DataTable dtCategorys = new DataTable();

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                categoryID = Int32.Parse(Request.QueryString["CategoryID"].ToString());
                this.ddlCategory.SelectedValue = categoryID.ToString();
            }
            catch (Exception ex)
            {
                categoryID = -1;
            }

            if (!Page.IsPostBack)
            {
                dtCategorys = CategoryProvider.GetCategorysForBackEnd().Tables[0];
                CreateDDLCategory(0, 0);
                this.ddlCategory.Items.Insert(0, new ListItem("--- Chose Category ---", "-1"));
                this.ddlCategory.SelectedValue = categoryID.ToString();
                Get_DDLSupplier();

                if (Request.QueryString["ProductID"] != null)
                {
                    try
                    {
                        ProductID = Int32.Parse(Request.QueryString["ProductID"].ToString());
                        
                    }
                    catch (Exception ex)
                    {
                        ProductID = -1;
                       
                    }
                }

                if (ProductID == -1)
                {
                    ViewState["action"] = HangSo.ACTION_ADD;

                }
                else
                {
                    Product theProduct = ProductProvider.GetProductsByProductID(ProductID);

                    if (theProduct == null)
                        Response.Redirect("AdminProducts.aspx");
                    else
                    {
                        this.ddlSupplier.SelectedValue = theProduct.SupplierID.ToString();
                        this.ddlCategory.SelectedValue = theProduct.CategoryID.ToString();
                        this.txtProductName.Text = theProduct.ProductName;
                        this.txtQuantityPerUnit.Text = theProduct.QuantityPerUnit.ToString();
                        this.txtPrice.Text = theProduct.Price.ToString();
                        this.txtPricePerUnit.Text = theProduct.PricePerUnit.ToString();
                        this.ImageProduct.ImageUrl = theProduct.PictureUrl.ToString();
                        ViewState["PictureUrl"] = theProduct.PictureUrl;
                        this.ddlUnitInStock.SelectedValue = theProduct.UnitsInStock.ToString();
                        this.txtDiscount.Text = theProduct.Discount.ToString();
                        this.FCKDecription.Value = theProduct.Description.ToString();
                        ViewState["ID"] = theProduct.ProductID;
                        ViewState["action"] = HangSo.ACTION_UPDATE;
                    }
                }
                trSupplier.Style["display"] = "none";
            }
        }

        /// <summary>
        /// Author : toanvt
        /// CreatedDate : 01/02/2012
        /// Description : tạo DropDownList bằng đệ quy
        /// </summary>
        /// <param name="parentID"></param>
        private void CreateDDLCategory(Int32 parentID, Int32 level)
        {
            String preString = "";

            for (Int32 i = 0; i < level; ++i)
            {
                preString += "--";
            }

            DataRow[] drCategorysSub = dtCategorys.Select("ParentID = " + parentID.ToString());
            Int32 amountOfCategorySub = drCategorysSub.Count();

            //Điểm dừng đệ quy
            if (amountOfCategorySub == 0)
                return;

            for (Int32 i = 0; i < amountOfCategorySub; ++i)
            {
                Int32 subCategoryID = Int32.Parse(drCategorysSub[i]["CategoryID"].ToString());

                ListItem li = new ListItem(preString + drCategorysSub[i]["CategoryName"].ToString(), drCategorysSub[i]["CategoryID"].ToString());
                this.ddlCategory.Items.Add(li);
                CreateDDLCategory(subCategoryID, level + 1);
            }
        }

        private void Get_DDLSupplier()
        {
            
            this.ddlSupplier.Items.Insert(0, new ListItem("Select Supplier ...", "-1"));

        }

        private Boolean ValidateData()
        {
            String message = "";
            Boolean isSuccess = true;
            string sExtendsion = ".gif|.GIF|.jpg|.JPG|.png|.PNG";

            try
            {
                if (this.fuPictureUrl.HasFile && sExtendsion.IndexOf(Path.GetExtension(fuPictureUrl.PostedFile.FileName))<0) {
                    isSuccess = false;
                    message = "Upload picture only.";
                }
            }
            catch (Exception ex)
            {
                isSuccess = false;
            }
            if (!isSuccess)
                ltrMessage.Text = message;

            return isSuccess;
        }


        /// <summary>
        /// Rezise anh truoc khi up len server
        /// Author: Chiennv
        /// Create date: 31/01/2912
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// 

        private ImageRezise getWidth(string File)
        {
            ImageRezise x = new ImageRezise();
            FileStream fs = new FileStream(File, FileMode.Open, FileAccess.Read, FileShare.Read);
            System.Drawing.Image image = System.Drawing.Image.FromStream(fs);
            try
            {
                int fileLength = Convert.ToInt32(fs.Length);
                int fileWidth = image.Width;
                int fileHeight = image.Height;
                x.m_W = fileWidth;
                x.m_H = fileHeight;
            }
            catch (Exception ex)
            {
                Response.Write("Error: " + ex.Message);
            }
            return x;
        }  

        /// <summary>
        /// Ham add product vao database
        /// Author: Chiennv
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            String action = ViewState["action"].ToString();

            if (!ValidateData())
                return;

            Page.Validate();

            if (Page.IsValid)
            {

                Product theProduct = new Product();
                //theProduct.DeletedFlag = this.cbDeletedFlag.Checked;
                theProduct.SupplierID = -1;
                theProduct.CategoryID = Int32.Parse(this.ddlCategory.SelectedValue);
                theProduct.ProductName = this.txtProductName.Text.Trim();
                theProduct.QuantityPerUnit = this.txtQuantityPerUnit.Text.Trim();
                theProduct.Price = float.Parse(this.txtPrice.Text.Trim());
                theProduct.PricePerUnit = float.Parse(this.txtPricePerUnit.Text.Trim());
                theProduct.UnitsInStock = this.ddlUnitInStock.SelectedValue.ToString();
                theProduct.Discount = float.Parse(this.txtDiscount.Text.Trim());
                theProduct.Description = FCKDecription.Value.ToString().Trim();
               

                if (this.fuPictureUrl.HasFile)
                {
                    String fileName = fuPictureUrl.PostedFile.FileName;                    
                    string str = Server.MapPath("~/");
                    str += "ImageDatas\\Products\\";
                    DirectoryInfo directory = new DirectoryInfo(str);

                    if (!directory.Exists)
                    {
                        DirectoryInfo drt = new DirectoryInfo("\\ImageDatas");
                        if (!drt.Exists)
                        {
                            directory = new DirectoryInfo(Server.MapPath("~/"));

                            directory = directory.CreateSubdirectory("ImageDatas");

                        }
                        directory = new DirectoryInfo(Server.MapPath("~/").ToString() + "\\ImageDatas");
                        directory = directory.CreateSubdirectory("Products");
                    }

                    // Rezise anh truoc khi up len server
                    // start

                    string _path = "D:\\Image\\Product\\"+fuPictureUrl.FileName;
                    int thumbWidth = 300;//default width
                    int thumbHeight = 225;//default height
                    //get height
                    ImageRezise __is = new ImageRezise();
                    __is = getWidth(_path);
                    double xmode = (double)__is.m_W / thumbWidth;
                    double xHeight = 0;
                    xHeight = __is.m_H / xmode;
                    thumbHeight = Convert.ToInt32(xHeight);
                    //save thumb
                    System.Drawing.Image oImg = System.Drawing.Image.FromStream(fuPictureUrl.PostedFile.InputStream);
                    System.Drawing.Image oThumbNail = new Bitmap(thumbWidth, thumbHeight, oImg.PixelFormat);

                    Graphics oGraphic = Graphics.FromImage(oThumbNail);
                    oGraphic.CompositingQuality = CompositingQuality.HighQuality;
                    oGraphic.SmoothingMode = SmoothingMode.HighQuality;
                    oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;

                    Rectangle oRectangle = new Rectangle(0, 0, thumbWidth, thumbHeight);
                    oGraphic.DrawImage(oImg, oRectangle);

                    string _pathThumb = Request.PhysicalApplicationPath + "ImageDatas//Products//" +fuPictureUrl.FileName;
                    oThumbNail.Save(_pathThumb, System.Drawing.Imaging.ImageFormat.Jpeg);
                    oImg.Dispose();
                    //end
                                     
                    theProduct.PictureUrl = "~//ImageDatas//Products//"+fuPictureUrl.FileName.Trim();
                }
                else
                {
                    if (action != HangSo.ACTION_ADD)
                    {
                        theProduct.PictureUrl = ViewState["PictureUrl"].ToString();
                    }
                    else
                    {
                        theProduct.PictureUrl = "~//ImageDatas//Products//noImage.gif";
                    }

                }
                if (action == HangSo.ACTION_ADD)
                {
                    theProduct.ProductID = -1;
                    ProductProvider.UIProduct(theProduct, true);
                }
                else
                {
                    theProduct.ProductID = Int32.Parse(ViewState["ID"].ToString());
                    ProductProvider.UIProduct(theProduct, false);
                }               
                Response.Redirect("AdminProducts.aspx?CategoryID=" + Int32.Parse(this.ddlCategory.SelectedValue));               
            }
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
           
            Response.Redirect("AdminProducts.aspx?CategoryID=" + Int32.Parse(this.ddlCategory.SelectedValue));           
        }

        protected void btnapply_Click(object sender, EventArgs e)
        {
            String action = ViewState["action"].ToString();

            if (!ValidateData())
                return;

            Page.Validate();

            if (Page.IsValid)
            {

                Product theProduct = new Product();
                //theProduct.DeletedFlag = this.cbDeletedFlag.Checked;
                theProduct.SupplierID = -1;
                theProduct.CategoryID = Int32.Parse(this.ddlCategory.SelectedValue);
                theProduct.ProductName = this.txtProductName.Text.Trim();
                theProduct.QuantityPerUnit = this.txtQuantityPerUnit.Text.Trim();
                theProduct.Price = float.Parse(this.txtPrice.Text.Trim());
                theProduct.PricePerUnit = float.Parse(this.txtPricePerUnit.Text.Trim());
                theProduct.UnitsInStock = this.ddlUnitInStock.SelectedValue.ToString();
                theProduct.Discount = float.Parse(this.txtDiscount.Text.Trim());
                theProduct.Description = FCKDecription.Value.ToString().Trim();


                if (this.fuPictureUrl.HasFile)
                {
                    String fileName = fuPictureUrl.PostedFile.FileName;
                    string str = Server.MapPath("~/");
                    str += "ImageDatas\\Products\\";
                    DirectoryInfo directory = new DirectoryInfo(str);

                    if (!directory.Exists)
                    {
                        DirectoryInfo drt = new DirectoryInfo("\\ImageDatas");
                        if (!drt.Exists)
                        {
                            directory = new DirectoryInfo(Server.MapPath("~/"));

                            directory = directory.CreateSubdirectory("ImageDatas");

                        }
                        directory = new DirectoryInfo(Server.MapPath("~/").ToString() + "\\ImageDatas");
                        directory = directory.CreateSubdirectory("Products");
                    }

                    // Rezise anh truoc khi up len server
                    // start

                    string _path = "D:\\Image\\Product\\" + fuPictureUrl.FileName;
                    int thumbWidth = 300;//default width
                    int thumbHeight = 225;//default height
                    //get height
                    ImageRezise __is = new ImageRezise();
                    __is = getWidth(_path);
                    double xmode = (double)__is.m_W / thumbWidth;
                    double xHeight = 0;
                    xHeight = __is.m_H / xmode;
                    thumbHeight = Convert.ToInt32(xHeight);
                    //save thumb
                    System.Drawing.Image oImg = System.Drawing.Image.FromStream(fuPictureUrl.PostedFile.InputStream);
                    System.Drawing.Image oThumbNail = new Bitmap(thumbWidth, thumbHeight, oImg.PixelFormat);

                    Graphics oGraphic = Graphics.FromImage(oThumbNail);
                    oGraphic.CompositingQuality = CompositingQuality.HighQuality;
                    oGraphic.SmoothingMode = SmoothingMode.HighQuality;
                    oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;

                    Rectangle oRectangle = new Rectangle(0, 0, thumbWidth, thumbHeight);
                    oGraphic.DrawImage(oImg, oRectangle);

                    string _pathThumb = Request.PhysicalApplicationPath + "ImageDatas//Products//" + fuPictureUrl.FileName;
                    oThumbNail.Save(_pathThumb, System.Drawing.Imaging.ImageFormat.Jpeg);
                    oImg.Dispose();
                    //end

                    theProduct.PictureUrl = "~//ImageDatas//Products//" + fuPictureUrl.FileName.Trim();
                }
                else
                {
                    if (action != HangSo.ACTION_ADD)
                    {
                        theProduct.PictureUrl = ViewState["PictureUrl"].ToString();
                    }
                    else
                    {
                        theProduct.PictureUrl = "~//ImageDatas//Products//noImage.gif";
                    }

                }
                if (action == HangSo.ACTION_ADD)
                {
                    theProduct.ProductID = -1;
                    ProductProvider.UIProduct(theProduct, true);
                }
                else
                {
                    theProduct.ProductID = Int32.Parse(ViewState["ID"].ToString());
                    ProductProvider.UIProduct(theProduct, false);
                }
                ltrMessage.Text = "Påfør suksess";
            }

        }
    }

}